package nbcp.web.product

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Value
import org.springframework.data.mongodb.core.query.Criteria
import nbcp.base.comm.*
import nbcp.db.mongo.entity.ProductInfo
import org.springframework.web.bind.annotation.RestController
import nbcp.base.extend.*
import nbcp.comm.JsonpMapping
import nbcp.db.IdName
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.SysCategory
import nbcp.web.MyHttpRequestWrapper
import javax.servlet.http.HttpServletRequest

/**
 * Created by Cy on 17-4-1.
 */

@Api(description = "商品信息", tags = arrayOf("ProductInfo"))
@RestController
@JsonpMapping("/info/product")
class ProductInfo_Controller {

    @Value("\${shop.uploadServer.host}")
    var uploadImageHost: String = "";

    //添加日志
    companion object {
        //private val logger = LoggerFactory.getLogger(ProductInfo_Controller::class.java)
    }

    //  xxx/productInfo/list
    @ApiOperation("查询所有商品")
    @JsonpMapping("/find")
    fun list(category: String,
             take: Int,
             skip: Int,
             request: MyHttpRequestWrapper
    ): ListResult<ProductInfo> {
        //从QueryModel中获取参数,调用Find方法查询
        //var resultes1 = mor.info.productInfo.find(query.skip, query.take, query.sortAsc, query.sortName, "corpId" match session.CorpId)
        var corpId = request.Corp.id;

        var categories = mutableListOf<String>()

        if (category.HasValue) {
            categories = mor.shop.sysCategory.query()
                    .select { it.code }
                    .where { it.pcode match category }
                    .toList(String::class.java)

            categories.add(category)
        }


        return mor.info.productInfo.query()
                .where { it.corp.id match corpId }
                .apply {
                    if (category.HasValue) {
                        this.where { it.category match_in categories }
                    }
                }
                .limit(skip, take)
                .orderBy { it.id.desc }
                .toListResult();
    }

    // xx/productInfo/add
    @ApiOperation("添加商品")
    @JsonpMapping("/add")
    fun add(@JsonModel product: ProductInfo, session: HttpServletRequest): ApiResult<String> {
        product.corp = session.Corp;

        mor.info.productInfo.insert(product);
        if (mor.affectRowCount != 1) {
            return ApiResult(msg = "添加商品出错")
        }

        return ApiResult.of(data = product.id)
    }

    // xx/productInfo/save
    @ApiOperation("修改商品,除图片，Sku部分")
    @JsonpMapping("/save")
    fun save(
            id: String,
            @JsonModel product: ProductInfo,
            session: HttpServletRequest
    ): JsonResult {
        if (id.HasValue == false) {
            return JsonResult(msg = "参数非法")
        }

        //执行更新
        var update = mor.info.productInfo.updateById(id);

        ProductInfo::class.java.AllFields.filter {
            if (List::class.java.isAssignableFrom(it.type)) return@filter false;
            if (it.name.IsIn(
                            mor.info.productInfo.id,
                            mor.info.productInfo.video,
                            mor.info.productInfo.images,
                            mor.info.productInfo.showImages,
                            mor.info.productInfo.parameters,
                            mor.info.productInfo.skuDefines,
                            mor.info.productInfo.skuStockPrice,
                            mor.info.productInfo.saleCount,
                            mor.info.productInfo.corp,
                            mor.info.productInfo.createAt

                    )) return@filter false;
            return@filter true;
        }.forEach {
            /*  if (it.name == "brand"){
                  update.set(it.name,IdName(product.brand.id,product.name))
              }else if (it.name == "category"){
                  update.set(it.name,StringCodeName(product.category.code,product.category.name))
              }else{
                  update.set(it.name, it.get(product))
              }*/
            it.isAccessible = true;
            update.set(it.name, it.get(product))
        }

        update.exec()

        return JsonResult()
    }

    // xx/productInfo/saveStatus
    @ApiOperation("修改商品状态")
    @JsonpMapping("/setStatus")
    fun saveStatus(productId: String, status: ProductStatusEnum, session: HttpServletRequest): JsonResult {
        mor.info.productInfo.updateById(productId)
                .set(mor.info.productInfo.status, status)
                .exec()

        if (mor.affectRowCount == 0) {
            return JsonResult("修改商品状态失败");
        }
        return JsonResult();
    }

    // xx/productInfo/get
    @ApiOperation("根据Id获取一个商品信息")
    @JsonpMapping("/get")
    fun getInfo(productId: String, session: HttpServletRequest, request: MyHttpRequestWrapper): ApiResult<ProductInfo> {

        var ret = ApiResult<ProductInfo>()

        var where = mutableListOf<Criteria>()

        var corpId = request.Corp.id;

        if (corpId.HasValue) {
            where.add(mor.info.productInfo.corp.id match corpId)
            println(corpId)
        }

        //根据商品id查询出对应的商品
        var productInfo = mor.info.productInfo.queryById(productId)
                .where(where)
                .toEntity();

        if (productInfo == null) {
            ret.msg = "找不到商品信息";
            return ret
        }
        ret.data = productInfo;

//        var corpInfo = mor.system.sysCorporation.findById(corpId)!!;
//        if (corpInfo.brand.HasValue) {
//            corpInfo.PatchHostUrl(uploadImageHost);
//
//            ret.value = BrandRef(id= "~", name = corpInfo.brand, url = corpInfo.brandLogo.url, slogan = corpInfo.brandSlogan);
//        }

        return ret;
    }


//        if (request.IsProxy == false) {
//            ret.value = mor.system.sysCorporation.queryById(request.CorpId)
//                    .select(mor.system.sysCorporation.brand)
//                    .select(mor.system.sysCorporation.brandLogo.toString())
//                    .toEntity()
//                    .let {
//                        BrandRef("~",
//                                name = it?.brand ?: "",
//                                url = it?.brandLogo?.url ?: "",
//                                slogan = it?.brandSlogan ?: "")
//                    }
//
//        }


    // category   code    name
    @ApiOperation("获取分类列表")
    @JsonpMapping("/categoryList")
    fun cateGoryList(): ApiResult<MutableList<SysCategory>> {
        val brands = mor.shop.sysCategory.query()
                .select(mor.shop.sysCategory.code)
                .select(mor.shop.sysCategory.name)
                .orderBy { it.order.asc }
                .orderBy { it.code.asc }
                .toList()
        return ApiResult.of(data = brands)
    }

}